// 1.引入createSlice 返回reducer和action
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";

// 3. 定义state
interface userState {
  token: string | null;
  loading: boolean; // 请求状态
  error: string | null; // 错误信息
}

const defaultState: userState = {
  token: null,
  loading: false,
  error: null,
};

// 4. 定义异步请求方法
export const signIn = createAsyncThunk(
  "user/signIn",
  async (params: { email: string; password: string }) => {
    // ! 使用createAsyncThunk的返回值 promise三种状态
    const { data } = await axios.post(`http://123.56.149.216:8080/auth/login`, {
      ...params,
    });
    return data.token;
  }
);

// 2. 放回slice
export const userSlice = createSlice({
  name: "user",
  initialState: defaultState,
  reducers: {
    logOut: (state) => {
      state.token = null;
      state.error = null;
      state.loading = false; // todo 竟然没有登出接口
    },
  },
  extraReducers: {
    // ! 使用createAsyncThunk的返回值 promise三种状态 必须使用extraReducers
    // 使用的是类型
    [signIn.pending.type]: (state) => {
      state.loading = true; // immer框架 内部的produce实现返回了一个新的object
    },
    [signIn.fulfilled.type]: (state, action) => {
      state.loading = false;
      state.token = action.payload; // 直接用payload传参来更新状态
      state.error = null;
    },
    [signIn.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false;
      state.error = action.payload;
    },
  },
});
